package com.richfit.barcodesystem_cczt.network.download;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {

    private static final String TAG = "DownloadUtil";

    /**
     * 带进度下载模式：DownloadProgressListener进度监听器
     *
     * @param url
     * @param listener
     */
    public static void download(Context mContext, final String url, String FileName, final DownloadProgressListener listener) {
        // 设置响应时间
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFailResponse();
                Log.i(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                File file = FileUtil.generateFile(url);
                ContextWrapper cw = new ContextWrapper(mContext.getApplicationContext());
                File directory = cw.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                File file = new File(directory, FileName);
                InputStream is = response.body().byteStream();   //相应体获得inputStream
                BufferedInputStream bis = new BufferedInputStream(is);//将inputstream转换成bufferedinputstream
                byte[] content = new byte[1024];
                int len = 0;                                          //每次读取长度
                long sumReaded = 0L;
                long contentSize = response.body().contentLength();   //下载文件总长度
                FileOutputStream fos = new FileOutputStream(file);    //创建fileOutputStream
                while ((len = bis.read(content)) != -1) {                 //循环获取字节流
                    fos.write(content, 0, len);                  //写入文件，读取byte[]中的缓存
                    sumReaded += len;                                 //获取已下载长度
                    listener.onDownloadProgress
                            (sumReaded, contentSize, len == -1); //监听下载进度，是否下载完成
                }
                listener.onDownloadResult(file.getAbsolutePath(), sumReaded, contentSize, len == -1);
                fos.flush();
                fos.close();
                bis.close();
                is.close();
            }
        });
    }

    public static void installAPK(Context mContext, String filePath, String fileName) {
        Log.i(TAG, "开始安装APP！");
        Log.i(TAG, filePath + ";" + fileName);

        setPermission(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File file = new File(filePath);
        String authority = mContext.getApplicationContext().getPackageName() + ".fileProvider";
        //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
        Uri apkUri = FileProvider.getUriForFile(mContext, authority, file);

        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);

    }

    //修改文件权限
    private static void setPermission(String absolutePath) {
        String command = "chmod " + "777" + " " + absolutePath;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

